package com.unknowpupil.alibaba.cloud.oauth.configure;

import com.unknowpupil.alibaba.cloud.oauth.integration.IntegrationAuthentication;
import com.unknowpupil.alibaba.cloud.oauth.integration.IntegrationAuthenticationContext;
import com.unknowpupil.alibaba.cloud.oauth.integration.authenticator.IntegrationAuthenticator;
import com.unknowpupil.alibaba.cloud.oauth.vo.SysUserAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 集成认证用户服务
 *
 * @author LIQIU
 * @date 2018-3-7
 **/
@Service
public class IntegrationUserDetailsService implements UserDetailsService {

    private List<IntegrationAuthenticator> authenticators;

    @Autowired(required = false)
    public void setIntegrationAuthenticators(List<IntegrationAuthenticator> authenticators) {
        this.authenticators = authenticators;
    }

    @Override
    public UserDetails loadUserByUsername(String str) throws UsernameNotFoundException {
        IntegrationAuthentication entity = IntegrationAuthenticationContext.get();
        if (entity == null){
            entity = new IntegrationAuthentication();
        }
        SysUserAuthentication dto = this.authenticate(entity);
        if (dto == null){
            throw new OAuth2Exception("用户名或密码错误");
        }

//        SysUserAuthentication user = new SysUserAuthentication();
//        user.setId(user.getId());
//        user.setWeChatNickname(user.getWeChatPhone());
//        user.setPassword(user.getPassword());
//        user.setWeChatPhone(user.getWeChatPhone());
        return dto;
    }

    private SysUserAuthentication authenticate(IntegrationAuthentication integrationAuthentication) {
        if (this.authenticators != null) {
            for (IntegrationAuthenticator authenticator : authenticators) {
                if (authenticator.support(integrationAuthentication)) {
                    return authenticator.authenticate(integrationAuthentication);
                }
            }
        }
        return null;
    }
}
